<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="btn1">发送连接</button>
    <button id="btn2">关闭连接</button>
    <script>
        let btn1 = document.querySelector('#btn1')
        let btn2 = document.querySelector('#btn2')
        // 1.wss有点类似是加密的连接
        let ws = new WebSocket('wss://javascript.info/article/websocket/demo/hello')
        // 2. 发送连接，发送一次，仍旧处于连接，就不能再次发送了
        btn1.addEventListener('click', (event) => {
            ws.send('发送连接111')
        })
        // 监听发送成功的消息
        ws.onopen = (event) => {
            console.log(event, '发送成功');
        }
        // 接受服务端消息
        ws.onmessage = (event) => {
            console.log(event, '接受服务端的消息'); // 服务端接受到消息后，也会发消息过来，这里接受服务端发送的消息
        }
        // 点击按钮，主动的去关闭连接
        btn2.addEventListener('click', (event) => {
            ws.close()
            console.log('主动的关闭连接去');
        })
        // 接受服务端停止的消息
        ws.onclose = (event) => {
            console.log('监听关闭连接的信息');
            console.log(event, 'event');
        }
    </script>
</body>
</html>